package kubeclient

import (
	"context"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"os/user"
	"path/filepath"
)


var (
	kubeconfig = "/root/.kube/config"
)

type Client struct {
	Clientset *kubernetes.Clientset
}

func NewClient()(*Client){
	user ,err := user.Current()
	if err == nil{
		kubeconfig = filepath.Join(user.HomeDir,".kube","config")
	}
	cfg,err := clientcmd.BuildConfigFromFlags("",kubeconfig)
	if err != nil{
		panic(err.Error())
	}
	clientset,err := kubernetes.NewForConfig(cfg)
	if err != nil{
		panic(err.Error())
	}

	return &Client{
		Clientset: clientset,
	}
}

func (c *Client)ListNode()(*v1.NodeList,error)  {
	nodeList,err := c.Clientset.CoreV1().Nodes().List(context.TODO(),metav1.ListOptions{})
	if err != nil{
		return nil, err
	}
	return nodeList,nil
}

func (c *Client)ListPod()(*v1.PodList,error){
	//option := metav1.ListOptions{
	//	FieldSelector: fmt.Sprintf("spec.nodeName=%s,status.phase!=Failed,status.phase!=Succeeded",nodeName),
	//}
	//Pods参数namespaces为空表示获取所有名称空间的pod
	podList,err := c.Clientset.CoreV1().Pods("").List(context.TODO(),metav1.ListOptions{})
	if err != nil{
		return nil, err
	}
	return podList,nil
}